<?php

namespace app\admin\controller\user;

use app\admin\model\Admin;
use app\admin\model\User as ModelUser;
use app\common\controller\Backend;
use app\common\model\User as CommonModelUser;
use Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Db;

/**
 * 服务商管理
 *
 * @icon fa fa-user
 */
class Agent extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $acctLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }
    public function index()
    {

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $op = $this->request->get("op", '');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $filter = $filter ? $filter : [];
            $map = [];
            if (isset($filter['puser.nickname']) && $filter['puser.nickname']) {
                $nickname = $filter['puser.nickname'];
                //待发货 待评价 待收货 已完成
                unset($filter['puser.nickname'], $op['puser.nickname']);
                $ids = ModelUser::whereLike('nickname', '%' . $nickname . '%')->column('id');
                //一定要有
                $this->request->get(['filter' => json_encode($filter)], ['op' => json_encode($op)]);
                $map['parent_id'] = ['in', $ids];
            }
            if ($this->auth->user_id) {
                $user = CommonModelUser::get($this->auth->user_id);
                if ($user && $user->is_agent) {
                    $this->model->where('find_in_set(:id,agent_area_ids)', ['id' => $user->agent_area_id])
                        ->where('agent_area_id', 'neq', $user->agent_area_id);
                    // $map['agent_area_id'] = ['neq', $user->agent_area_id];
                }
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['lev'])
                ->where('is_agent', 1)
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->puser;
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $user = CommonModelUser::get($this->auth->user_id);
            $this->view->assign('agent_area_ids', explode(',', $user->agent_area_ids ?? ''));
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['acct_id'] = $this->auth->acct_id;
        if ($this->request->post('area')) {
            $params['agent_area_id'] = $this->request->post('area');
            $params['agent_area_ids'] = implode(',', [$this->request->post('province'), $this->request->post('city'), $this->request->post('area')]);
        } elseif ($this->request->post('city')) {
            $params['agent_area_id'] = $this->request->post('city');
            $params['agent_area_ids'] = implode(',', [$this->request->post('province'), $this->request->post('city')]);
        } elseif ($this->request->post('province')) {
            $params['agent_area_id'] = $this->request->post('province');
            $params['agent_area_ids'] = implode(',', [$this->request->post('province')]);
        } else {
            $params['agent_area_id'] = '';
            $params['agent_area_ids'] = '';
        }
        $params['is_agent'] = 1;
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $has = Admin::where('mobile', $params['mobile'])->find();
            if ($has) {
                exception('管理员手机号已存在');
            }
            $has = CommonModelUser::where('agent_area_id', $params['agent_area_id'])->value('id');
            if ($has) {
                exception('该区域已有服务商');
            }
            $data = [
                'username' => $this->model->mobile,
                'user_id' => $this->model->id,
                'nickname' => $this->model->nickname,
                'mobile' => $this->model->mobile,
                'status' => 'normal',
            ];
            $admin = Admin::create($data);
            $dataset = [];
            $group_id = 8;

            if (count(explode(',', $params['agent_area_ids'])) > 1) {
                $group_id = 9;

                if ($this->auth->user_id) {
                    $user = CommonModelUser::get($this->auth->user_id);
                    if ($user) {
                        if ($user->agent_rate < $params['agent_rate']) {
                            exception('费率不能大于上级费率');
                        }
                    }
                }
            }
            // foreach ($group as $value) {
            $dataset[] = ['uid' => $admin->id, 'group_id' => $group_id];
            // }
            model('AuthGroupAccess')->saveAll($dataset);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }



    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['agent_area_ids'] = explode(',', $row['agent_area_ids']);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->token();

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($this->request->post('area')) {
                $params['agent_area_id'] = $this->request->post('area');
                $params['agent_area_ids'] = implode(',', [$this->request->post('province'), $this->request->post('city'), $this->request->post('area')]);
            } elseif ($this->request->post('city')) {
                $params['agent_area_id'] = $this->request->post('city');
                $params['agent_area_ids'] = implode(',', [$this->request->post('province'), $this->request->post('city')]);
            } elseif ($this->request->post('province')) {
                $params['agent_area_id'] = $this->request->post('province');
                $params['agent_area_ids'] = implode(',', [$this->request->post('province')]);
            } else {
                $params['agent_area_id'] = '';
                $params['agent_area_ids'] = '';
            }

            if ($this->auth->user_id) {
                $user = CommonModelUser::get($this->auth->user_id);
                if ($user) {
                    if ($user->agent_rate < $params['agent_rate']) {
                        exception('费率不能大于上级费率');
                    }
                }
                if (count(explode(',', $params['agent_area_ids'])) <= 1) {
                    exception('必须选择城市');
                }
            }
            $has = CommonModelUser::where('agent_area_id', $params['agent_area_id'])->where('id', 'neq', $this->auth->user_id)->value('id');
            if ($has) {
                exception('该区域已有服务商');
            }
            // $params['agent_area_ids'] =
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function commission()
    {
        $this->model = new \app\common\model\user\Commission();
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->get("filter", '');
            $op = $this->request->get("op", '');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $filter = $filter ? $filter : [];
            $map = [];
            if (isset($filter['user_id']) && $filter['user_id']) {
            } else {
                if ($this->auth->user_id) {
                    $this->model->where('user_id', $this->auth->user_id);
                }
            }


            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where('type', 'agent')
                ->order($sort, $order)
                // ->fetchSql(true)->select();var_dump($list);die;
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
}
